const express = require("express");
const app = express();
var cookie_parser = require("cookie-parser");
const body = require("body-parser");
var dev = express.Router();
var fs = require("fs");
var dayjs = require("dayjs");
var multiparty = require("multiparty");
app.use("/public", express.static("public"));
app.use(body.json()); //body-parser 解析json格式数据
app.use(cookie_parser());
dev.get("/", function (req, res) {
  res.json({
    name: "妍妍",
    age: 23,
    sex: "女",
    ai_hao: ["打代码"],
  });
});
dev.get("/get", function (req, res) {
  res.send("测试本地请求了/get");
});
dev.get("/list", function (req, res) {
  console.log("已有访问1");
  res.json({
    msg: "测试本地123",
    code: -1,
    ...req.cookies,
  });
});
dev.post("/add", function (req, res) {
  res.json({
    code: 0,
    msg: "测试本地请求了 /add",
    body: {
      ...req.body,
    },
  });
});
dev.post("/upla", (req, res) => {
  // 接收文件上传
  let form = new multiparty.Form({
    maxFilesSize: 500 * 1024 * 1024,
    uploadDir: "./public", //指定上传的文件路径
  });
  let name = null;
  form.parse(req, (err, field, files) => {
    console.log(files);
    for (let i = 0; i <= files.file.length - 1; i++) {
      let obj = files.file[i];
      name = new Date().getTime();
      fs.renameSync(obj.path, "./public/" + name + ".txt");
      res.json({
        url: `/public/${name}.txt`,
      });
    }
  });
  form.on("field", (name, value) => {
    // name:字段名
    // value:值
    // console.log("数据:", name, value);
  });
  //接收文件数据
  form.on("file", (name, file) => {
    console.log("文件:", name, file);
  });
  //表单解析完成
  form.on("close", () => {
    console.log("完成");
  });
});
app.use("*", function (req, res, next) {
  // res.setHeader("token", req.headers["token"]);
  // res.setHeader("Access-Control-Allow-Credentials", "true");
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
  res.header("Access-Control-Allow-Headers", "*");
  next();
});

app.use("/dev-api", dev);
app.listen(5001, function () {
  console.log("启动");
});
